Skip to content

fix: Prevent close from failing or hanging when called from a listener - #581

Merged
keelerm84 merged 5 commits into
mainfrom
mk/SDK-3566/close-from-listener
Dec 3, 2026
Merged

keelerm84 merged 5 commits into
mainfrom
mk/SDK-3566/close-from-listener

Conversation

@keelerm84

@keelerm84 keelerm84 commented Nov 13, 2026 •

Copy link
Copy Markdown
Member

Summary

Closing the client from inside a listener now works on every thread the SDK calls listeners on.

  • FDv2 stop joined each of its threads, including the one running the listener. The join raised, so the data store and big segment store were left open. Stop now skips the current thread, which exits on its own.
  • A flag change listener called by an override update held the override sink lock, and close waited for that lock forever. Listeners are now notified after the lock is released.
  • The FDv1 file data source with watchdog called listeners on the observer thread, and stop joined that thread. Stop now skips that join.
  • A close during a store update no longer lets the update write to the closed persistent store.

Note

Overview
Makes client.close() / stop() safe when invoked from flag-change, data-store, or file-reload listener threads.

FDv2 skips join() on the current thread during shutdown and bails out of in-flight synchronizer handling once stop is set so status is not flipped back from OFF. The Store tracks _closed and blocks further persistence to the backing feature store. OverrideSinkImpl uses a close Event (no lock on close), applies layer updates under the lock, and notifies listeners only after the lock is released. The file data source watchdog path skips joining the observer when stop runs on that same thread.

New tests cover stopping FDv2 from a flag listener, closing the sink from a notify callback, close vs in-progress snapshots, file auto-update close paths, and full client close from flag/data-store listeners.

Reviewed by Cursor Bugbot for commit 52cb4dc. Bugbot is set up for automated code reviews on this repo. Configure here.

… listener

Listeners run on a data system thread, and stopping the FDv2 data system joined every one of its
threads, including that one. The join raised, so the data store and big segment store were left
open.
…stener

A flag change listener called by an override update held the override sink lock, and close waited
for that lock forever. Listeners are now notified after the lock is released.

The FDv1 file data source with watchdog called listeners on the observer thread, and stop joined
that thread. Stop now skips the join on that thread.

A close from a listener during Store.apply let apply write the change set to the closed persistent
store. The store now stops persisting after close.
@keelerm84
keelerm84 requested a review from a team as a code owner November 13, 2026 16:27

@cursor cursor Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Risk: medium.

Automated risk review (dry run): Medium

This PR would not be automatically approved. Human approval required.

Why: This changes core client close/stop behavior across FDv2 thread join, the file data source observer thread, override-sink lock ordering, and persistent-store writes after close. Those interacting lifecycle paths are bounded by tests, but they are not a narrow low-risk change.

If you disagree with this review, share this PR in #feedback-agent-approvals or submit a changes-requested review explaining why.

Human review is needed and no reviewers were assigned.

Open in Web View Automation 

Sent by Cursor Approval Agent: Dry-Run PR Approver

@cursor cursor Bot added the risk:medium label Nov 13, 2026
@kinyoklion

Copy link
Copy Markdown
Member

Note: This comment was written by an AI assistant (Claude), at a reviewer's request.

Deadlock: closing the client from a listener while an override snapshot is being applied

This PR fixes the hang when an override listener closes the client. A related hang remains: a listener that fires on a LaunchDarkly update closes the client while the override source is applying a snapshot. Two threads take the store lock and the override sink lock in opposite order. The base commit has the same lock order, so this PR does not introduce it. But it is a listener thread on which close still does not work.

FDv2-synchronizers thread               override source thread
-------------------------               ----------------------
                                        sink.set_overrides()
                                          holds the sink lock
Store.apply()                             _apply() -> snapshot_merged_view()
  holds Store._lock
  _send_change_events()
    flag change listener
      client.close()
        FDv2.stop()
          override_sink.close()
            waits for the sink lock       base.all(kind)
                                            _ReadOnlyStoreView.all()
                                              get_active_store()
                                                waits for Store._lock

Impact: close() never returns. Every flag read also goes through get_active_store(). So once the two threads are stuck, variation() calls on all other threads block too.

When it happens: all three of these at once:

  • An override source is configured.
  • A listener closes the client in response to a LaunchDarkly update. This can be a flag change listener, or a data store status listener after a failed persistent write, which also runs under Store._lock.
  • The override source is computing a snapshot at that moment.

The window is about one snapshot computation, which reads all flags and segments twice, so it grows with the size of the environment. It is rare, but when it happens the client hangs.

Reproduction (forces the timing with a sleep)

Run with the path to a checkout of this branch as the first argument.

import sys, time, threading
sys.path.insert(0, sys.argv[1])
from ldclient import Context, datasystem
from ldclient.client import Config, LDClient
from ldclient.integrations.test_datav2 import TestDataV2

class Src:
    def start(self, sink):
        self.sink = sink
    def close(self):
        pass

class Builder:
    def __init__(self): self.src = Src()
    def build(self, config): return self.src

b = Builder()
td = TestDataV2.data_source()
td.update(td.flag('flag').on(True))
cfg = datasystem.custom().synchronizers(td.builder).overrides(b).build()
client = LDClient(Config('SDK_KEY', send_events=False, datasystem_config=cfg), start_wait=5)
assert client.is_initialized()

done = threading.Event()
def override_writer():
    b.src.sink.set_overrides({'other': {'key': 'other', 'version': 1, 'on': True, 'variations': [True], 'fallthrough': {'variation': 0}}}, {})

def listener(change):
    if change.key != 'flag' or done.is_set():
        return
    # The override source supplies a snapshot at this moment.
    threading.Thread(target=override_writer, daemon=True).start()
    time.sleep(0.3)
    client.close()
    done.set()

client.flag_tracker.add_listener(listener)
threading.Thread(target=lambda: td.update(td.flag('flag').on(False)), daemon=True).start()
print('close returned:', done.wait(4))
res = []
ev = threading.Thread(target=lambda: res.append(client.variation('flag', Context.create('u'), 'default')), daemon=True)
ev.start(); ev.join(3)
print('evaluation on another thread returned:', not ev.is_alive(), res)

On d17de3d, 3 of 3 runs print close returned: False and evaluation on another thread returned: False []. A faulthandler dump shows one thread at sink.py:73 close (under fdv2.py:358 stop and store.py:375 _send_change_events) and the other at store.py:410 get_active_store (under sink.py:117 snapshot_merged_view and sink.py:60 set_overrides).

Proposed fix

Make OverrideSinkImpl.close non-blocking. It only needs to stop later snapshots, so it can set an event instead of taking the sink lock:

@@ -49,11 +49,12 @@
         self._notify = notify
         self._has_listeners = has_listeners
         self._lock = threading.Lock()
-        self._closed = False  # guarded by _lock
+        # An event, not a flag guarded by _lock, so close never waits for _lock.
+        self._closed = threading.Event()
 
     def set_overrides(self, flags: Dict[str, Any], segments: Dict[str, Any]) -> None:  # type: ignore[override]
         with self._lock:
-            if self._closed:
+            if self._closed.is_set():
                 log.debug("Ignoring an override snapshot supplied after the override source was closed")
                 return
             try:
@@ -70,8 +71,9 @@
         Stops accepting snapshots. Used when the client is closed: a snapshot that the source
         supplies while it shuts down is ignored. The layer keeps its contents.
         """
-        with self._lock:
-            self._closed = True
+        # Does not take _lock. A listener can close the client while another thread holds
+        # _lock and waits for the store lock that the listener's thread holds.
+        self._closed.set()
 
     def close_and_clear(self) -> None:
         """
@@ -80,7 +82,7 @@
         overrides, and a late snapshot from the closed source is ignored.
         """
         with self._lock:
-            self._closed = True
+            self._closed.set()
             affected = self._apply({}, {})
         self._notify_all(affected)

Trade-off: close() no longer waits for a snapshot that has already passed the closed check. That snapshot still reaches the layer, and it can do so after close() returns. With this PR, that snapshot's notifications can already arrive after close(), so the change relaxes the guarantee a little further. A snapshot supplied after close() is still ignored. The close docstring could say that a snapshot already in progress completes.

Alternative: Store.apply could notify flag change listeners after it releases Store._lock, which is the same change this PR makes in the sink. That removes the problem on the store side as well. But it is a bigger change, because LaunchDarkly change notifications are currently ordered by that lock.

Verified: I applied the patch to d17de3d. With it, the reproduction returns from close() and from the evaluation in 3 of 3 runs, and 1979 unit tests pass. The database-integration test modules were not run.

# Conflicts:
#	ldclient/testing/impl/datasystem/test_fdv2_datasystem.py
Stop now sets the status to OFF. When a flag change listener closes the
client, the synchronizer thread returned from the store apply and set the
status of that update over OFF. The synchronizer loop now checks for stop
after the apply.
…ing an override update

A listener that closes the client runs while the store lock is held. If
the override source applied a snapshot at the same time, that thread held
the sink lock and waited for the store lock, and close waited for the sink
lock. The sink close no longer takes the sink lock. A snapshot that is
already in progress completes, and later snapshots are ignored.
@keelerm84

Copy link
Copy Markdown
Member Author

Thanks, confirmed. Your reproduction hung on the branch after merging main. I applied your proposed fix as written in 52cb4dc: OverrideSinkImpl.close now sets an event and does not take the sink lock. The close docstring states the trade-off: a snapshot that is already in progress completes, and its notifications can arrive after close() returns. With the fix, the reproduction passes 3 of 3 runs. I also added test_sink_close_does_not_wait_for_a_snapshot_in_progress, which fails without the fix.

The merge with main also exposed a separate problem. #584 made stop() set the data source status to OFF. When a listener calls stop() on the synchronizer thread, that thread then wrote the VALID status of the update over OFF. 6390c08 makes the synchronizer loop check for stop after the store apply.

@cursor cursor Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Risk: medium. SDK rules 1–3 pass (not a release PR, allowed author, no disallowed workflow changes), but the approval threshold is low only, so this is not approved. Cursor Bugbot completed with no findings; human review is needed and no reviewers were assigned.

Open in Web View Automation 

Sent by Cursor Approval Agent: SDK - Pull Request Router and Approver

@keelerm84
keelerm84 merged commit da24298 into main Dec 3, 2026
16 checks passed
@keelerm84
keelerm84 deleted the mk/SDK-3566/close-from-listener branch December 3, 2026 21:04
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants